package com.yx.fx.sys.web.api;

import cn.hutool.core.util.StrUtil;
import com.yx.fx.common.model.response.Outcome;
import com.yx.fx.sys.web.business.SysBusiness;
import com.yx.fx.sys.web.model.Login;
import com.yx.fx.sys.web.model.Token;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.validation.Valid;

import static com.yx.fx.common.constant.BaseConstant.AUTHORIZATION;


/**
 * @author 杨智杰
 * @date 2021/8/12 16:31
 */
@RestController
@Api(tags = "系统入口")
@RequestMapping("/sys")
public class SysApi {

    @Resource
    private SysBusiness sysBusiness;

    @ApiOperation("登录")
    @PostMapping("/login")
    public Outcome<Token> login(@RequestBody @Valid Login param) {
        return sysBusiness.login(param);
    }

    @ApiOperation("注销")
    @GetMapping("/logout")
    public Outcome logout() {
        String token = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest().getHeader(AUTHORIZATION);
        if (StrUtil.isNotBlank(token)) {
            sysBusiness.logout(token);
        }
        return Outcome.success("已注销!");
    }

    /**
     * 验证是否登录
     *
     * @return 是否登录
     */
    @GetMapping("/loginCheck")
    public Boolean loginCheck() {
        String token = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
                .getRequest().getHeader(AUTHORIZATION);
        return sysBusiness.loginCheck(token);
    }

    @RequestMapping("/notLogin")
    public Outcome notLogin() {
        return Outcome.success("未登录!").setCode(401);
    }

    @RequestMapping("/nonAuthority")
    public Outcome nonAuthority() {
        return Outcome.success("无权限!").setCode(403);
    }
}
